#!/usr/bin/env python
# ----------------------------------------------------------------------
# Numenta Platform for Intelligent Computing (NuPIC)
# Copyright (C) 2013, Numenta, Inc.  Unless you have an agreement
# with Numenta, Inc., for a separate license for this software code, the
# following terms and conditions apply:
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 3 as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
# See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see http://www.gnu.org/licenses.
#
# http://numenta.org/licenses/
# ----------------------------------------------------------------------

"""Git pre-commit hook.

Currently does the following checks:
  * Runs unit tests.
  * Checks for pylint errors.
"""

import os
import subprocess
import sys


def runTests(rootDir):
  try:
    subprocess.check_call([os.path.join(rootDir, 'run_tests.sh')])
  except subprocess.CalledProcessError:
    print ('Please fix unit tests before committing.  If this is in '
           'error, you can override with "git commit --no-verify ...".')
    sys.exit(1)


def checkLint():
  # Get a list of non-deleted Python files modified since last commit.
  sub = subprocess.Popen('git diff --staged --name-only HEAD'.split(),
                         stdout=subprocess.PIPE)
  sub.wait()
  py_files_changed = [file for file in [f.strip() for f in
                                        sub.stdout.readlines()]
                      if (file.endswith('.py') and os.path.exists(file)) or
                          isPythonScript(file)]

  for file in py_files_changed:
    try:
      subprocess.check_call(['pylint', '--errors-only', file])
    except subprocess.CalledProcessError:
      print ('Please fix pylint errors before committing.  If this is in '
             'error, you can override with "git commit --no-verify ...".')
      sys.exit(1)


def isPythonScript(filename):
  """Returns True if a file is a python executable."""
  if not os.access(filename, os.X_OK):
    return False
  else:
    try:
      first_line = open(filename, 'r').next().strip()
      return '#!' in first_line and 'python' in first_line
    except StopIteration:
      return False


def main():
  sub = subprocess.Popen('git rev-parse --show-toplevel'.split(), stdout=subprocess.PIPE)
  sub.wait()
  rootDir = sub.stdout.readlines()[0].strip()

  runTests(rootDir)
  checkLint()


if __name__ == '__main__':
  main()
